<?php
/**
 * 商品评论
 * @author 戚银
 * @email thinkercode@sina.com
 * @date 2015年8月21日 下午1:51:50
 */
class DiscussApp extends MallbaseApp{

	/**
	 * 获取评论列表
	 *
	 * @access public
	 * @return void
	 */
	public function index(){
		$action = '获取评论列表';
		setLogParameter($action);
		$method = strtoupper($_SERVER['REQUEST_METHOD']);
		if ($method != 'GET') {
			$this->ajax_return(FLAG_ERROR, '非法操作！');
		}

		/* 取得列表数据 */
		$goods_id = $this->get_gp('goods_id', 'G');
		$offset = $this->get_gp('offset', 'G');
		$size = $this->get_gp('size', 'G');
		$offset = $offset ? intval($offset) : 0;
		$size = $size ? intval($size) : 10;
        //获取评论信息
		$sql = "SELECT a.content,a.add_time,b.user_name,b.nickname,b.portrait FROM ".DB_PREFIX."comments AS a INNER JOIN
				".DB_PREFIX."member AS b ON (a.user_id = b.user_id)
				WHERE a.goods_id='{$goods_id}' and a.type=1 and a.if_examine=1 and a.if_show=1
				ORDER BY a.id DESC LIMIT {$offset},{$size}";
		$discuss = m('comments')->getAll($sql);

		$data = array();
		foreach($discuss as $v){
			$data[] = array(
				'user_name' => $v['user_name'] ? $v['user_name'] : $v['nickname'],
				'portrait' => $v['portrait'] ? substr($v['portrait'],0,7)!="http://" && substr($v['portrait'],0,8)!="https://" ? QINIU_URL.$v['portrait'] : $v['portrait'] : '',
				'content' => $v['content'],
				'add_time' => $v['add_time']
			);
		}

		if($data){
			$this->ajax_return(FLAG_OK, '', $data);
		}else{
			$this->ajax_return(FLAG_OK, '没有商品评论');
		}
	}

	/**
	 * 评论商品
	 * @access public
	 * @return void
	 */
	public function comment(){
		$action = '评论商品';
		setLogParameter($action);
		$method = strtoupper($_SERVER['REQUEST_METHOD']);
		if ($method != 'POST') {
			$this->ajax_return(FLAG_ERROR, '非法操作！');
		}

		// 获取数据
		$user_id = $this->checkLogin();
		$goods_id = $this->get_gp('goods_id', 'P');
		$content = $this->get_gp("content","P");
		if(!$user_id){
			$this->ajax_return(ERROR_LOGIN, '用户没有登录！');
		}

		if(!$goods_id){
			$this->ajax_return(FLAG_ERROR, '评论商品不存在');
		}

		if(!$content){
			$this->ajax_return(FLAG_ERROR, '评价内容不能为空');
		}

		if(m('comments')->add(array('type'=>1, 'user_id'=>$user_id, 'goods_id'=>$goods_id,'content'=>$content, 'add_time'=>time()))){
			$this->ajax_return(FLAG_OK, '评论成功');
		}else{
			$this->ajax_return(FLAG_OK, '评论失败');
		}
	}
}